package product;

import java.awt.Color;
import java.awt.Dimension;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.RefineryUtilities;

import java.awt.BorderLayout;

import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingConstants;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class LineCahrt extends JInternalFrame {

	Connection con;
	int dept2, dept1;
	DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
	int cnt;
	boolean graflag = false;
	JFreeChart chart;
	SearchPro sc;
	Date nal;
	String str;
	ProductMain2 pm;
	String last_year = null;
	private JMenuBar menuBar;
	private JPanel panel;
	private JPanel panel_1;
	private JPanel panel_2;
	private JComboBox comboBox;
	private JComboBox comboBox_1;
	private JComboBox comboBox_2;
	private JComboBox comboBox_3;
	private JPanel panel_3;
	private JLabel lblNewLabel;
	private JTextField findstr;
	private JButton btnNewButton;
	private JPanel panel_4;
	private JButton btnNewButton_1;
	String y,m;
	SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
	
	public LineCahrt(ProductMain2 pm,Connection c){
		super("꺽은선 그래프",true,true,true,true);
		this.pm = pm;
		this.con= c;
		
		try {
			DbCon();
			setJMenuBar(getMenuBar_1());
			
			ChartPanel chartpanel = new ChartPanel(chart);
			chartpanel.setDisplayToolTips(true);
			chartpanel.setPreferredSize(new Dimension(500, 270));
			setContentPane(chartpanel);		
			chartpanel.setLayout(null);
			
			year();
			nal = new Date();
			
	        m=sd.format(nal).substring(5,7);
	        comboBox_1.setSelectedItem(m);
	        comboBox_3.setSelectedItem(m);
			
	        gra();
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	void DbCon()throws Exception{
		Class.forName("oracle.jdbc.driver.OracleDriver");
		System.out.println("드라이버 로딩 성공...");
		String url="jdbc:oracle:thin:@192.168.10.4:1521:XE";

		String user="hr";
		String pwd="hr";

		con=DriverManager.getConnection(url,user,pwd);
		System.out.println("DB 연결 성공!");
	}
	
public void year(){
		
		String sql = "select s_date from stock order by s_date asc";
		
		try{
			PreparedStatement pstmt = con.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			
			Date db_date = null;
			last_year = null;
			
			while(rs.next()){
				db_date = rs.getDate(1); // 쿼리로부터의 날짜 데이터를 읽어온다. 
			}
			
			last_year = sd.format(db_date);
			last_year = last_year.substring(0, 4); // 년도만 짤라용 
			
			String combo_year1 = (String) comboBox.getItemAt(1);
			String combo_year2 = (String) comboBox_2.getItemAt(1);
			
			int db_year = Integer.parseInt(last_year);
			int com_year1 = Integer.parseInt(combo_year1);
			int com_year2 = Integer.parseInt(combo_year2);
			
			while (com_year1 < db_year){
				// 콤보박스에 있는 년도보다 데베에 있는 년도가 더 크다면 
				comboBox.addItem(++com_year1);
				comboBox_2.addItem(++com_year2);
			}
			
			comboBox.setSelectedIndex(comboBox.getModel().getSize() - 1);
			comboBox_2.setSelectedIndex(comboBox_2.getModel().getSize() - 1);
			
			
			// 다썼으니깐 닫아
			rs.close();
			pstmt.close();
			
		
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}

	public void gra(){
		if(graflag == false){
//			dataSet = new DefaultCategoryDataset();  // DataSet 값을 넣는다...

			// ********** Chart 설정  **********

			String xAxisLabel = "Term";  // x축 이름
			String yAxisLabel = "Total Stock";  // y축 이름
			String title = "graph of broken line";  // 차트 이름
			PlotOrientation pOrientation = PlotOrientation.VERTICAL;


			chart = ChartFactory.createLineChart(title, xAxisLabel, yAxisLabel, dataSet, pOrientation, false, true, false);
			chart.setBackgroundPaint(Color.white);
			CategoryPlot plot = (CategoryPlot) chart.getPlot();
			plot.setBackgroundPaint(Color.lightGray);
			plot.setRangeGridlinePaint(Color.white);

			NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
			rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

			LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
			// renderer.setShapesVisible(true);
			renderer.setDrawOutlines(true);
			renderer.setUseFillPaint(true);
			//setJMenuBar(getMenuBar_1());

			// ********** Chart 설정  **********

			ChartPanel chartPanel = new ChartPanel(chart);
			chartPanel.setPreferredSize(new Dimension(500, 500));
			setContentPane(chartPanel);
			chartPanel.setLayout(new BorderLayout(0, 0));
		}

		else{
			try{
				
//				dataSet = new DefaultCategoryDataset();  // DataSet 값을 넣는다...
				String year1=comboBox.getSelectedItem()+""+comboBox_1.getSelectedItem()+"";
				String year2=comboBox_2.getSelectedItem()+""+comboBox_3.getSelectedItem()+"";

				int num1=Integer.parseInt(year1);
				int num2=Integer.parseInt(year2);
				str = findstr.getText();
				Statement st=con.createStatement();

				for(int i = num1 ; i<num2+1; i++){
					dept1 = 0;
					dept2 = 0;
					String sql1 = " select sa_pro_code, nvl(sum(sa_ea),0) from sale where to_char(sa_reg_date,'yyyymm')=? "
							+ "group by sa_pro_code";
					PreparedStatement pstmt1 = con.prepareStatement(sql1);
					pstmt1.setInt(1, i);
					ResultSet rs1=pstmt1.executeQuery();
					while(rs1.next()){
						if(rs1.getString(1).equals(str)){
							if(rs1.getString(2) == null){
								dept1 = 0;
							}else{
								dept1 = Integer.parseInt(rs1.getString(2));
							}
						}
					}    	  
					String sql2 = " select code, nvl(sum(ea),0) from product where to_char(nal,'yyyymm') = ?"
							+ " group by code";
					PreparedStatement pstmt2 = con.prepareStatement(sql2);
					pstmt2.setInt(1, i);
					ResultSet rs2=pstmt2.executeQuery();
					while(rs2.next()){
						if(rs2.getString(1).equals(str)){
							if(rs2.getString(2) == null){
								dept2 = 0;
							}else{
								dept2 = Integer.parseInt(rs2.getString(2));
							}
						}
					}
					String ab = Integer.toString(i).substring(0,4);
					String ab1 = Integer.toString(i).substring(4, 6);
					String Day = ab+"-"+ab1;

					dataSet.addValue((dept2-dept1), str, Day);
				}
				
				String xAxisLabel = "Term";  // x축 이름
				String yAxisLabel = "Total Stock";  // y축 이름
				String title = "graph of broken line";  // 차트 이름
				PlotOrientation pOrientation = PlotOrientation.VERTICAL;


				JFreeChart chart = ChartFactory.createLineChart(title, xAxisLabel, yAxisLabel, dataSet, pOrientation, false, true, false);
				chart.setBackgroundPaint(Color.white);
				CategoryPlot plot = (CategoryPlot) chart.getPlot();
				plot.setBackgroundPaint(Color.lightGray);
				plot.setRangeGridlinePaint(Color.white);

				NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
				rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

				LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
				//			renderer.setShapesVisible(true);
				renderer.setDrawOutlines(true);
				renderer.setUseFillPaint(true);
				setJMenuBar(getMenuBar_1());

				// ********** Chart 설정  **********

				ChartPanel chartPanel = new ChartPanel(chart);
				//			chartPanel.setVisible(false);
				chartPanel.setPreferredSize(new Dimension(500, 500));
				setContentPane(chartPanel);
				chartPanel.setLayout(new BorderLayout(500, 500));
				chartPanel.updateUI();

			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}

	public static void main(String[] args) 
	{

	}
	private JMenuBar getMenuBar_1() {
		if (menuBar == null) {
			menuBar = new JMenuBar();
			menuBar.add(getPanel());
			menuBar.add(getBtnNewButton_1());
		}
		return menuBar;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getPanel_3(), BorderLayout.WEST);
			panel.add(getPanel_4(), BorderLayout.EAST);
			panel.add(getFindstr(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getComboBox_2(), BorderLayout.WEST);
			panel_1.add(getComboBox_3(), BorderLayout.EAST);
		}
		return panel_1;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setLayout(new BorderLayout(0, 0));
			panel_2.add(getComboBox(), BorderLayout.WEST);
			panel_2.add(getComboBox_1(), BorderLayout.EAST);
		}
		return panel_2;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setPreferredSize(new Dimension(60, 21));
			
			comboBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				}
			});
			comboBox.setModel(new DefaultComboBoxModel(new String[] {"","2010"}));
		}
		return comboBox;
	}
	private JComboBox getComboBox_1() {
		if (comboBox_1 == null) {
			comboBox_1 = new JComboBox();
			comboBox_1.setPreferredSize(new Dimension(45, 21));
			comboBox_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				}
			});
			comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
		}
		return comboBox_1;
	}
	private JComboBox getComboBox_2() {
		if (comboBox_2 == null) {
			comboBox_2 = new JComboBox();
			comboBox_2.setPreferredSize(new Dimension(60, 21));
			comboBox_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				}
			});
			comboBox_2.setModel(new DefaultComboBoxModel(new String[] {"","2010"}));
		}
		return comboBox_2;
	}
	private JComboBox getComboBox_3() {
		if (comboBox_3 == null) {
			comboBox_3 = new JComboBox();
			comboBox_3.setPreferredSize(new Dimension(45, 21));
			comboBox_3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
				}
			});
			comboBox_3.setModel(new DefaultComboBoxModel(new String[] {"", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"}));
		}
		return comboBox_3;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(new BorderLayout(0, 0));
			panel_3.add(getPanel_2(), BorderLayout.WEST);
			panel_3.add(getLblNewLabel(), BorderLayout.CENTER);
			panel_3.add(getPanel_1(), BorderLayout.EAST);
		}
		return panel_3;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel(" ~ ");
		}
		return lblNewLabel;
	}
	private JTextField getFindstr() {
		if (findstr == null) {
			findstr = new JTextField();
			findstr.setColumns(10);
		}
		return findstr;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("검색");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					graflag = true;
					gra();
				}
			});
		}
		return btnNewButton;
	}
	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setLayout(new BorderLayout(0, 0));
			panel_4.add(getBtnNewButton(), BorderLayout.EAST);
		}
		return panel_4;
	}

	
	public void OpenPro(){
		try {
			SearchPro sc = new SearchPro(pm);
			sc.setBounds(622, 213,150, 398);
			sc.setVisible(true);
			sc.setAlwaysOnTop(true);
		} catch (Exception e1) {
		
			e1.printStackTrace();
		}
		
	}
	
	public void setData(String s){
		findstr.setText(s);
	}
	
	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("제품조회");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					OpenPro();
				}
			});
		}
		return btnNewButton_1;
	}
}



